package main

import (
	"fmt"
	"sync"
)

func doWork(id int, w *worker) {

	for n := range w.in {
		fmt.Printf("Worker %d received %c\n", id, n)
		w.done()
	}
}

type worker struct {
	in   chan int
	done func() // go 的函数是一等公民，当然可以作为类型
}

/*
创建worker
*/
func createWorker(id int, wg *sync.WaitGroup) *worker {

	w := &worker{
		in: make(chan int),
		// 定义其 done 属性值为一个函数，做sync.WaitGroup.Done() 操作
		done: func() {
			wg.Done()
		},
	}
	go doWork(id, w)
	return w
}

func chanDemo() {

	var wg sync.WaitGroup
	var workers [10]*worker
	for i := 0; i < 10; i++ {
		workers[i] = createWorker(i, &wg)
	}
	for i, worker := range workers {
		wg.Add(1)
		worker.in <- 'a' + i
	}
	for i, worker := range workers {
		wg.Add(1)
		worker.in <- 'A' + i
	}

	// 等待任务组结束
	wg.Wait()
}

func main() {
	chanDemo()
}
